from flask import current_app, render_template, session, jsonify, request, g
from info.constants import CLICK_RANK_MAX_NEWS
from info.response_code import RET
from . import index_bp
from info import redis_store
from info.models import User, News, Category
from info.utility.commont.filter import get_user


@index_bp.route('/')
@get_user
def index():
    user = g.user
    user_dict = user.to_dict() if user else None
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(CLICK_RANK_MAX_NEWS)
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    click_news_list = []
    category_list = []
    for new in news_list if news_list else []:
        click_news_list.append(new.to_dict())
    for category in categories if categories else []:
        category_list.append(category.to_dict())
    data = {
        'user_info': user_dict,
        'click_news_list': click_news_list,
        'categories': category_list
    }
    return render_template('news/index.html', data=data)


@index_bp.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')


@index_bp.route('/news_list')
def news():
    cid = request.args.get('cid')
    p = request.args.get('page', 1)
    per_page1 = request.args.get('per_page', 10)
    if not cid:
        return jsonify(errno=RET.PARAMERR, errmsg='格式错误')
    try:
        cid = int(cid)
        p = int(p)
        per_page1 = int(per_page1)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="数据错误")
    items = []
    current_p = 1
    total_page = 1
    list1 = []
    if cid != 1:
        list1.append(News.category_id == cid)
    try:
        paginate = News.query.filter(*list1).order_by(News.create_time.desc()).paginate(page=p, per_page=per_page1, error_out=False)
        items = paginate.items
        current_p = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻列表 错误")
    news_dict_list = []
    for new in items if items else []:
        news_dict_list.append(new.to_dict())
    data = {
        'news_list': news_dict_list,
        'current_page': current_p,
        'total_page': total_page
    }
    return jsonify(errno=RET.OK, errmsg='查询成功', data=data)

